//
//  HLSeeMoreViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/6.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLMicroCourseController.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "MBProgressHUD+HL.h"
#import "HLUserInfo.h"
#import "HLSeeMoreCell.h"
#import "HLMoreCourse.h"
#import "HLCourseFoldViewController.h"
#import "HLFoldCourse.h"
#import "HLArticleViewController.h"
#import "HLCourseDetailViewController.h"
#import "HLCourseCollectionCell.h"

#define kPageLimit 10

@interface HLMicroCourseController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSUInteger _currenPage;
}
@property (nonatomic ,strong) UICollectionView *collectionView;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation HLMicroCourseController

#pragma mark - Lazy

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - UI

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    [self setupRefresh];
}

- (void)setUI
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    CGFloat margin = 10;
    CGFloat itemW = (ScreenWidth - 2 * margin - 5) * 0.5;
    CGFloat itemH = itemW;
    layout.itemSize = CGSizeMake(itemW, itemH );
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = HLRGB(245, 245, 245);
    _collectionView.contentInset = UIEdgeInsetsMake(10 , 10, 74, 10);
    [_collectionView registerClass:[HLCourseCollectionCell class]  forCellWithReuseIdentifier:@"HLCourseCollectionCell"];
    [self.view addSubview:_collectionView];
}

- (void)setupRefresh
{
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    
    [self.collectionView.mj_header beginRefreshing];
    [self.collectionView.mj_header setAutomaticallyChangeAlpha:YES];
    self.collectionView.mj_footer.hidden = YES;
}


#pragma mark - Request

- (void)loadNewUsers
{
    [self cancerRequest];
    
    /**** 数据清空 ****/
    [self.dataSource removeAllObjects];
    
    _currenPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetCourseByType signStr];
    params[@"userid"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    params[@"type"] = @(self.index);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetCourseByType parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        [weakSelf.collectionView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            weakSelf.dataSource = [HLMoreCourse mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.collectionView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            weakSelf.collectionView.mj_footer.hidden = NO;
            if (weakSelf.dataSource.count < kPageLimit) {
                _currenPage--;
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                /**** 重置底部状态 ****/
                [weakSelf.collectionView.mj_footer endRefreshing];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

- (void)loadMoreUsers
{
    [self cancerRequest];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetCourseByType signStr];
    params[@"userid"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    params[@"type"] = @(self.index);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetCourseByType parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        [weakSelf.collectionView.mj_footer endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            NSMutableArray *tempArray = [NSMutableArray array];
            tempArray = [HLMoreCourse mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
            [weakSelf.collectionView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            if (tempArray.count < kPageLimit) {
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.collectionView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HLCourseCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HLCourseCollectionCell" forIndexPath:indexPath];
    if (self.dataSource.count  >= indexPath.row + 1) {
        cell.moreCourse = self.dataSource[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HLMoreCourse *more = self.dataSource[indexPath.row];
    HLFoldCourse *foldCourse = [HLFoldCourse new];
    if ([more.type integerValue] == 1 ) {
        foldCourse.wkid = more.ID ;
        HLArticleViewController *article = [HLArticleViewController new];
        article.foldCourse = foldCourse;
        [self.navigationController pushViewController:article animated:YES];
    }
    if ([more.type integerValue] == 0) {
        foldCourse.wkid = more.ID;
        HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
        couseDetail.foldCourse = foldCourse;
        [self.navigationController pushViewController:couseDetail animated:YES];
    }
}

#pragma mark - Private

- (void)cancerRequest
{
    /**** 取消之前的请求 ****/
    [[HTTPRequestManager defaultManager].sessionManager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

/***** 界面销毁 取消请求 ****/
- (void)dealloc
{
    [self cancerRequest];
}

@end
